﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using WebPWrapper;
using WebPWrapper.Encoder;

namespace MX.Core.Webp
{
    public class WebpUtils
    {
        public static bool FromImage(Bitmap sourceImage, out byte[] webpData)
        { 
            bool encoded = false;
            webpData = null;
            try
            { 
               // WebPExecuteDownloader.Download();//会自动下载webm项目的二进制文件
                var builder = new WebPEncoderBuilder();

                var encoder = builder.Build(); // 建立編碼器
                using (var outputStream = new MemoryStream())
                using (var inputStream = new MemoryStream())
                {
                    sourceImage.Save(inputStream, sourceImage.RawFormat);
                    inputStream.Flush();
                    inputStream.Position = 0;
                    encoder.Encode(inputStream, outputStream); // 編碼
                    outputStream.Position = 0;
                    webpData = outputStream.ToArray();
                }
                encoded = true;
            }
            catch (Exception ex)
            {
                Log.Logger.Default.Error(ex, "webp编码错误");
            }
            return encoded;
        }

    }
}
